package com.aabte.nettyleran.netty.http.xml;

import com.aabte.nettyleran.netty.http.xml.entity.Order;
import com.aabte.nettyleran.netty.http.xml.entity.OrderFactory;
import com.aabte.nettyleran.netty.http.xml.httpdecoder.HttpXmlResponseDecoder;
import com.aabte.nettyleran.netty.http.xml.httpencoder.HttpXmlRequestEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/14
 */
public class HttpXmlClient {

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        new HttpXmlClient().connect("127.0.0.1", port);
    }

    private void connect(String host, int port) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        sc.pipeline().addLast("http-decoder", new HttpResponseDecoder());
                        sc.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65535));
                        sc.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true));
                        sc.pipeline().addLast("http-encoder", new HttpRequestEncoder());
                        sc.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder());
                        sc.pipeline().addLast("xml-client-handler", new HttpXmlClientHandler());
                    }
                });

        try {
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    private static class HttpXmlClientHandler extends SimpleChannelInboundHandler<HttpXmlResponse> {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            HttpXmlRequest httpXmlRequest = new HttpXmlRequest(null, OrderFactory.createOrder(1L));
            ctx.writeAndFlush(httpXmlRequest);
        }

        @Override
        protected void messageReceived(ChannelHandlerContext ctx, HttpXmlResponse msg) throws Exception {
            System.out.println("The client receive response of http header is: " + msg.getHttpResponse().headers().names());
            System.out.println("The client receive response of http boyd is: " + msg.getResult());
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
}
